public class MainActivity extends ActionBarActivity {
// 데이터를 받아올 PHP 주소
String url = "http://172.200.110.113:80/android/data.php";
// 데이터를 보기위한 TextView
TextView tv;
// PHP를 읽어올때 사용할 변수
public GettingPHP gPHP;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gPHP = new GettingPHP();
tv = (TextView)findViewById(R.id.aaa);
gPHP.execute(url);
}
...
class GettingPHP extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
StringBuilder jsonHtml = new StringBuilder();
try {
URL phpUrl = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection)phpUrl.openConnection();
if ( conn != null ) {
conn.setConnectTimeout(10000);
conn.setUseCaches(false);
if ( conn.getResponseCode() == HttpURLConnection.HTTP_OK ) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ( true ) {
String line = br.readLine();
if ( line == null )
break;
jsonHtml.append(line + "\n");
}
br.close();
}
conn.disconnect();
}
} catch ( Exception e ) {
e.printStackTrace();
}
return jsonHtml.toString();
}
protected void onPostExecute(String str) {
try {
// PHP에서 받아온 JSON 데이터를 JSON오브젝트로 변환
JSONObject jObject = new JSONObject(str);
// results라는 key는 JSON배열로 되어있다.
JSONArray results = jObject.getJSONArray("results");
String zz = "";
zz += "Status : " + jObject.get("status");
zz += "\n";
zz += "Number of results : " + jObject.get("num_result");
zz += "\n";
zz += "Results : \n";
for ( int i = 0; i < results.length(); ++i ) {
JSONObject temp = results.getJSONObject(i);
zz += "\tdoc_idx : " + temp.get("doc_idx");
zz += "\tmember_idx : " + temp.get("member_idx");
zz += "\tsubject : " + temp.get("subject");
zz += "\tcontent : " + temp.get("content");
zz += "\treg_date : " + temp.get("reg_date");
zz += "\n\t--------------------------------------------\n";
}
tv.setText(zz);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}